/*
 * quark_wicket
 * @(#)FeedbackAlertPanel.java			Aug 25, 2008
 * 
 * Auteur : ATD
 * 
 * Copyright (c) 2008 Holy-Dis
 * 
 */
package adc.app.ui.wicket;

import java.util.Collections;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.feedback.FeedbackMessagesModel;
import org.apache.wicket.feedback.IFeedback;
import org.apache.wicket.feedback.IFeedbackMessageFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.util.string.JavaScriptUtils;

public class AlertFeedbackPanel extends Panel implements IFeedback {

	private static final long serialVersionUID = 1L;

	public class AlertModel extends AbstractReadOnlyModel<String> {

		private static final long serialVersionUID = 1L;

		@Override
		public String getObject() {
			String message = "";
			for (FeedbackMessage m : getCurrentMessages()) {
				if (filtre == null || filtre.accept(m)) {
					message += m.getMessage().toString() + "\\n";
				}
			}
			message = "alert('" + JavaScriptUtils.escapeQuotes(message) + "')";

			return message;
		}
	}

	private Label jsComp;
	private IFeedbackMessageFilter filtre;

	public AlertFeedbackPanel(String id, IFeedbackMessageFilter filtre) {
		super(id);
		setOutputMarkupId(true);
		setDefaultModel(newFeedbackMessagesModel());
		jsComp = new Label("js", new AlertModel()) {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isVisible() {
				return anyMessage();
			}
		};
		jsComp.setEscapeModelStrings(false);
		add(jsComp);
	}

	public AlertFeedbackPanel(String id) {
		this(id, null);
	}

	/**
	 * Search messages that this panel will render, and see if there is any
	 * message.
	 * 
	 * @return whether there is any message for this panel
	 */
	public final boolean anyMessage() {
		return !getCurrentMessages().isEmpty();
	}

	/**
	 * Gets the currently collected messages for this panel.
	 * 
	 * @return the currently collected messages for this panel, possibly empty
	 */
	protected final List<FeedbackMessage> getCurrentMessages() {
		@SuppressWarnings("unchecked")
		final List<FeedbackMessage> messages = (List<FeedbackMessage>) getDefaultModelObject();
		return Collections.unmodifiableList(messages);
	}

	/**
	 * Gets a new instance of FeedbackMessagesModel to use.
	 * 
	 * @return Instance of FeedbackMessagesModel to use
	 */
	protected FeedbackMessagesModel newFeedbackMessagesModel() {
		return new FeedbackMessagesModel(this);
	}

	public void majAjax(AjaxRequestTarget cible) {
		cible.appendJavaScript(String.valueOf(get("js").getDefaultModelObject()));
	}

}
